package com.system.service;

import com.system.entity.Score;
import com.system.entity.DataException;
import com.system.util.FileUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 成绩服务类
 * 处理成绩信息的增删改查
 */
public class ScoreService {
    private static final String SCORE_FILE = "score.txt";
    private StudentService studentService = new StudentService();
    private CourseService courseService = new CourseService();

    /**
     * 添加成绩
     * @param score 成绩对象
     * @throws DataException 数据异常
     */
    public void addScore(Score score) throws DataException {
        // 验证学生是否存在
        if (!studentService.isStudentExists(score.getStudentId())) {
            throw new DataException("该学号不存在，请先添加学生信息");
        }

        // 验证课程是否存在
        if (!courseService.isCourseExists(score.getCourseId())) {
            throw new DataException("该课程号不存在，请先添加课程信息");
        }

        // 验证分数
        if (score.getScore() < 0 || score.getScore() > 100) {
            throw new DataException("分数必须在0-100之间");
        }

        Score[] scores = FileUtil.readFromFile(SCORE_FILE, Score.class);
        
        // 检查是否已存在该学生该课程的成绩
        for (Score s : scores) {
            if (s.getStudentId().equals(score.getStudentId()) && 
                s.getCourseId().equals(score.getCourseId())) {
                throw new DataException("该学生该课程的成绩已存在");
            }
        }

        // 添加新成绩
        List<Score> scoreList = new ArrayList<>();
        for (Score s : scores) {
            scoreList.add(s);
        }
        scoreList.add(score);

        FileUtil.writeToFile(SCORE_FILE, scoreList.toArray(new Score[0]));
    }

    /**
     * 修改成绩
     * @param studentId 学号
     * @param courseId 课程号
     * @param newScore 新分数
     * @throws DataException 数据异常
     */
    public void updateScore(String studentId, String courseId, double newScore) throws DataException {
        // 验证分数
        if (newScore < 0 || newScore > 100) {
            throw new DataException("分数必须在0-100之间");
        }

        Score[] scores = FileUtil.readFromFile(SCORE_FILE, Score.class);
        List<Score> scoreList = new ArrayList<>();
        boolean found = false;

        for (Score score : scores) {
            if (score.getStudentId().equals(studentId) && score.getCourseId().equals(courseId)) {
                score.setScore(newScore);
                scoreList.add(score);
                found = true;
            } else {
                scoreList.add(score);
            }
        }

        if (!found) {
            throw new DataException("该学生该课程的成绩不存在");
        }

        FileUtil.writeToFile(SCORE_FILE, scoreList.toArray(new Score[0]));
    }

    /**
     * 删除成绩
     * @param studentId 学号
     * @param courseId 课程号
     * @throws DataException 数据异常
     */
    public void deleteScore(String studentId, String courseId) throws DataException {
        Score[] scores = FileUtil.readFromFile(SCORE_FILE, Score.class);
        List<Score> scoreList = new ArrayList<>();
        boolean found = false;

        for (Score score : scores) {
            if (!(score.getStudentId().equals(studentId) && score.getCourseId().equals(courseId))) {
                scoreList.add(score);
            } else {
                found = true;
            }
        }

        if (!found) {
            throw new DataException("该学生该课程的成绩不存在");
        }

        FileUtil.writeToFile(SCORE_FILE, scoreList.toArray(new Score[0]));
    }

    /**
     * 按学号查询学生所有成绩
     * @param studentId 学号
     * @return 成绩数组
     */
    public Score[] getScoresByStudentId(String studentId) {
        Score[] scores = FileUtil.readFromFile(SCORE_FILE, Score.class);
        List<Score> resultList = new ArrayList<>();

        for (Score score : scores) {
            if (score.getStudentId().equals(studentId)) {
                resultList.add(score);
            }
        }

        return resultList.toArray(new Score[0]);
    }

    /**
     * 按课程号查询所有学生成绩
     * @param courseId 课程号
     * @return 成绩数组
     */
    public Score[] getScoresByCourseId(String courseId) {
        Score[] scores = FileUtil.readFromFile(SCORE_FILE, Score.class);
        List<Score> resultList = new ArrayList<>();

        for (Score score : scores) {
            if (score.getCourseId().equals(courseId)) {
                resultList.add(score);
            }
        }

        return resultList.toArray(new Score[0]);
    }

    /**
     * 计算平均分
     * @param scores 成绩数组
     * @return 平均分
     */
    public double calculateAverage(Score[] scores) {
        if (scores == null || scores.length == 0) {
            return 0;
        }

        double sum = 0;
        for (Score score : scores) {
            sum += score.getScore();
        }

        return sum / scores.length;
    }
}